#include "mysocket.h"

#define MAX_BUFFER	1024
#define QUEUE_SIZE	10

MySocket::MySocket(int port) {
	int error;
	#if defined WIN32
//	WSADATA wsaData;
//
//	error = WSAStartup(MAKEWORD(2,0), &wsaData);	
//	
//	if (error != 0) {
//		printf("Unable to find a usable dll\n");
//		m_hSocket = SOCKET_ERROR;
//		throw "Winsock DLL not found";
//	}
	#endif

	Address.sin_addr.s_addr = INADDR_ANY;
	Address.sin_family      = AF_INET;
	Address.sin_port        = htons(port);

	printf("Creating SERVER socket..\n");
	if ((hServerSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) {
		printf("Could not create a SERVER socket...\n");
		return;
	}
	else {
		//printf("OK\n");
	}
	printf("Binding socket...\n");
	error = 10048;
	while (error != 0){// == 10048) {
		//printf("%i\n", hServerSocket);
		if ((bind(hServerSocket, (struct sockaddr*)&Address, sizeof(Address))) == SOCKET_ERROR) {
		//	printf("Could not bind the SERVER socket...\n");
			error = errno;//WSAGetLastError();
		//	printf("error = %i\n", error);
			printf(".");
			//printf("%i\n", hServerSocket);

			#if defined WIN32
			//Sleep(1000);
			#endif
			usleep(1000 * 1000);
		}
		else {
			error = 0;
			printf("\n" );
		}
	}

	//Listening queue
	listen(hServerSocket, QUEUE_SIZE);
//	printf("Waiting for connection...\n");
}

MySocket::~MySocket() {
	close(m_hSocket);
	Address.sin_addr.s_addr = NULL;
	Address.sin_family = NULL;
	Address.sin_port = NULL;
	close(hServerSocket);
}

void MySocket::AcceptEm() {
	printf("waiting to accept client...");
	int thesize = sizeof(Address);
	m_hSocket = accept(hServerSocket, (struct sockaddr*)&Address,(socklen_t *) &thesize);

	if (m_hSocket == INVALID_SOCKET)
		printf("couldn't accept socket correctly\n");
//	printf("Connection received with hSocket = %i\n", m_hSocket);
	printf("accepted\n");
}

int MySocket::SendMessage(char *message, int len) {
	int bsent = 0;

	//printf("message sending: %s, socket = %i\n", message, m_hSocket);
	if ((bsent = send(m_hSocket, message, len, 0)) == SOCKET_ERROR) {
		printf("error sending socket message: %s\n", message);
		//close(hServerSocket);
		//close(m_hSocket);
		//exit(0);
	}
	//printf("bsent = %i\n", bsent);

	return 1;
}

int MySocket::SendMessage(char *num,char *message, int len) {
	int bsent = 0;

	//printf("num: %s\n", num);

//	printf("message sent: %s\n", message);
	if ((bsent = send(m_hSocket, num, sizeof(int), 0)) == SOCKET_ERROR) {
		printf("error sending socket message\n");
		exit(0);
		//quit = true;
	}
	//printf("bsent = %i\n", bsent);
	int bsent2 = 0;
	//printf("message: %s\n", message);

	if ((bsent2 = send(m_hSocket, message, len, 0)) == SOCKET_ERROR) {
		printf("error sending socket message\n");
		exit(0);
		//quit = true;
	}

	return bsent;
}

int MySocket::ReadMessage(char *message) {
	memset(message, 0, MAX_BUFFER);

	int NumBytes = recv(m_hSocket, message, MAX_BUFFER, 0);

	if (NumBytes == SOCKET_ERROR) {
		fprintf(stderr,"Socket Error reading message\n");
		//close(m_hSocket);
		//close(hServerSocket);
		//throw "Error Reading From Socket";
	}

	return NumBytes;
}

int MySocket::ReadMessageInt(char *message) {
	int NumBytes = 0;

	memset(message, 0, MAX_BUFFER);
	NumBytes = recv(m_hSocket, message, sizeof(int), 0);
	//printf("NumBytesinteger = %i\n", NumBytes);
	if (NumBytes == SOCKET_ERROR) {
		//quit = true;
		printf("lost socket connection\n");
		exit(0);
//		fprintf(stderr,"Socket Error\n");
//		throw "Error Reading From Socket";
	}

	return NumBytes;
}

void MySocket::buildmsg(char *message,char *mensaje) {
	
	int n = 0;
	memset(mensaje, 0, 1024);
	mensaje[0] =2;
	mensaje[8] =2;
	mensaje[12] =1;
	mensaje[16] =7;
	int m = 20+(int)strlen(message)*2;
	for (int i = 20 ; i<m; i = i+2)
	{
		mensaje[i] = message[n];
		n++;
	}
}

void MySocket::sendmsg(double score) {

	char mensaje[1024], length[1024],msg[1024];
	sprintf(mensaje,"%f\0", score);
	
	//strcpy(mensaje,"1.2");
	int len = (int)strlen(mensaje) * 2 + 20;
	sprintf(length, "%c\0", (char)len);
	length[2] = length[3] = '\0';
	buildmsg(mensaje,msg);
	SendMessage(length, msg, 20+2*(int)strlen(mensaje));
}

int MySocket::readmsg() {

	char filename[1024],length[1024];
	char* message; 

	int	len = 0;
	while (len < 1)
		len = ReadMessageInt(length);

	len = 0;
	int junk = (int)length[0];
	junk = (junk - 20)/2;
	message = new char [junk];
	
	//printf("length of the message: %i\nsize of message: %i\n", junk,strlen(message));
	while (len < 1)
		len = ReadMessage(filename);

	int l = 0;
	for (int j = 20; j < 20+junk*2; j=j+2) { 
		
		message[l] = filename[j];
		l++;	
	}
	int m = atoi(message);
	//printf("msg = %i\n", m);
	//delete length ;
	delete message ;
	//delete filename ;

	return m;
}

void MySocket::readmsg(char *buf) {

	char filename[1024],length[1024];
	char* message; 

	int	len = 0;
	while (len < 1)
		len = ReadMessageInt(length);

	len = 0;
	int junk = (int)length[0];
	junk = (junk - 20)/2;
	message = new char [junk];
	
	//printf("length of the message: %i\nsize of message: %i\n", junk,strlen(message));
	while (len < 1)
		len = ReadMessage(filename);

	int l = 0;
	for (int j = 20; j < 20+junk*2; j=j+2) { 	
		message[l] = filename[j];
		l++;	
	}
	message[l] = '\0';
	strcpy(buf, message);
}
